package com.googlecode.svnj.dav;

public class Path {

    private Path() { }
    
    /** join two path elements ensuring the result is separated by exactly one '/' */
    public static String join(String parent, String child) {
        StringBuilder ret = new StringBuilder();
        if (parent == null) parent = "";
        int len = parent.length();
        if (len > 0 && parent.charAt(len - 1) == '/') {
            parent = parent.substring(0, len - 1);
        }
        ret.append(parent);
        // don't append child if its the empty string
        if (child != null && child.length() > 0) {
            ret.append('/');
            if (child.charAt(0) == '/')
                child = child.substring(1);
            ret.append(child);
        }
        return ret.toString();
    }
    
    /** after the first occurance of '/', not including the '/' itself
     * e.g:
     *  '/a/b/c' -> 'a/b/c'
     *  'a/b/c' -> 'b/c'
     *  '/' -> '' 
     */
    public static String subpath(String path) {
        String ret = null;
        int ind = path.indexOf('/');
        if (ind != -1) {
            ret = path.substring(ind + 1);
        }
        return ret;
    }

    /** parse up to the first non-digit as a long */
    public static long atol(String s, long defalt) {
        long ret = defalt;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                sb.append(c);
            } else {
                break;
            }
        }
        if (sb.length() > 0) {
            ret = Long.parseLong(sb.toString());
        }
        return ret;
    }
}
